package com.conferenceroom.interceptor;



import com.conferenceroom.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 如果返回的是一个false，表示要拦截该请求，反之放行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("uri:" + request.getRequestURI());
        String method = request.getMethod();
        if ("GET".equals(method) || "OPTIONS".equals(method)) {
            return true;
        }
        //获取token
        String token = request.getHeader("Authorization");//获取token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        if (!StringUtils.hasLength(token)) {
//            throw new RuntimeException("token 不能为空");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            response.getWriter().write("{\"code\": 401, \"message\": \"Token is required\"}"); // 返回 JSON 信息
            response.setContentType("application/json;charset=UTF-8"); // 设置响应类型为 JSON
            return false;
        }

        //验证token
        if (!jwtUtil.verifyToken(token)){
//            throw new RuntimeException("token 验证失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为 401
            response.getWriter().write("{\"code\": 401, \"message\": \"Invalid token\"}"); // 返回 JSON 信息
            response.setContentType("application/json;charset=UTF-8"); // 设置响应类型为 JSON// 设置状态码为 401
            return false;
        }
        return true;
    }
}
